<template>
  <div class="app-container">
    <el-card shadow="never" class="mainCard" v-loading="loading">
      <!-- <div style="width: 100%; height: 40px;">
                <el-button type="warning" size="small" link style="float: right; margin-left: 10px;" @click="reback()">
                    返回
                </el-button>
            </div> -->
      <div>
        <el-tabs v-model="activeName" @tab-click="handleTabsClick">
          <el-tab-pane label="供者信息" name="first">
            <el-descriptions title="供者信息">
              <el-descriptions-item label="姓名">
                <h3>{{ checkedData.name }}</h3>
              </el-descriptions-item>
              <el-descriptions-item label="昵称">
                <h3>{{ checkedData.nickName }}</h3>
              </el-descriptions-item>
              <el-descriptions-item label="性别">
                <h3>{{ checkedData.sex == 0 ? '女' : '男' }}</h3>
              </el-descriptions-item>
              <el-descriptions-item label="生日">
                <h3>{{ checkedData.birthday }}</h3>
              </el-descriptions-item>
              <el-descriptions-item label="手机号">
                <h3>{{ checkedData.phone }}</h3>
              </el-descriptions-item>
            </el-descriptions>
            <el-descriptions title="供者问卷信息" :column="1" style="margin-top: 1%;">
              <el-descriptions-item v-for="item in answerJsonList" :key="item.key" :label="item.key">
                <h3>{{ item.val }}</h3>
              </el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>
          <el-tab-pane label="体检信息" name="third">
            <div v-if="!checkup_info">
              <template>
                <el-button style="margin-bottom: 10px;" type="success" @click="openAddCheckUpDialog()">
                  <i class="el-icon-circle-plus"></i>新增体检</el-button>
              </template>
              <el-table v-loading="loading" :data="seqSampleList" highlight-current-row border>
                <el-table-column label="序号" width="55" prop="dataIndex" />
                <el-table-column label="体检编号" prop="number" />
                <el-table-column label="创建时间" prop="createTimeText" />
                <el-table-column label="更新时间" prop="updateTimeText" />
                <el-table-column fixed="right" label="操作" min-width="280" width="280">
                  <template #default="scope">
                    <el-button type="primary" size="small" link @click="openDetailCheckUpDialogVisible(scope.row.id)"><i
                        class="el-icon-view"></i>
                      查看</el-button>
                    <el-button type="warning" size="small" link @click="openAddCheckUpDialog(scope.row.id)"><i
                        class="el-icon-edit-outline"></i>
                      编辑</el-button>
                    <el-button type="success" size="small" link @click="previewReport(scope.row)"><i
                      class="el-icon-view"></i> 预览报告</el-button>
                  </template>
                </el-table-column>
              </el-table>

              <div class="block" style="float: right;margin-top: 20px;">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                  :current-page="queryParams.pageNum" :page-sizes="[10, 20, 50, 100]" :page-size="10"
                  layout="total, sizes, prev, pager, next, jumper" :total="total">
                </el-pagination>
              </div>
            </div>
            <checkupReport v-if="checkup_info" :dataCheckupId="checkedDataID" @close="closeDetail"></checkupReport>
          </el-tab-pane>

          <el-tab-pane label="打卡信息" name="third2">
            <el-table v-loading="loading" :data="signInList" highlight-current-row border>
              <el-table-column label="序号" width="55" prop="dataIndex" />
              <el-table-column label="打卡时间" prop="createTimeText" />
              <el-table-column label="早餐图片" prop="bImgNum">
                <template #default="scope">
                  <template v-if="scope.row.bImgNum == 0">-</template>
                  <template v-else>
                    <a href="javascript:;" @click="openSignInDetail(scope.row, 'B')">{{ scope.row.bImgNum }} 张</a>
                  </template>
                </template>
              </el-table-column>
              <el-table-column label="午餐图片" prop="lImgNum">
                <template #default="scope">
                  <template v-if="scope.row.lImgNum == 0">-</template>
                  <template v-else>
                    <a href="javascript:;" @click="openSignInDetail(scope.row, 'L')">{{ scope.row.lImgNum }} 张</a>
                  </template>
                </template>
              </el-table-column>
              <el-table-column label="晚餐图片" prop="dImgNum">
                <template #default="scope">
                  <template v-if="scope.row.dImgNum == 0">-</template>
                  <template v-else>
                    <a href="javascript:;" @click="openSignInDetail(scope.row, 'D')">{{ scope.row.dImgNum }} 张</a>
                  </template>
                </template>
              </el-table-column>
              <el-table-column label="粪便图片" prop="fImgNum">
                <template #default="scope">
                  <template v-if="scope.row.fImgNum == 0">-</template>
                  <template v-else>
                    <a href="javascript:;" @click="openSignInDetail(scope.row, 'F')">{{ scope.row.fImgNum }} 张</a>
                  </template>
                </template>
              </el-table-column>
            </el-table>
            <div class="block" style="float: right;">
              <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="queryParams.pageNum" :page-sizes="[10, 20, 50, 100]" :page-size="10"
                layout="total, sizes, prev, pager, next, jumper" :total="total">
              </el-pagination>
            </div>
          </el-tab-pane>

          <el-tab-pane label="捐献样本" name="second">
            <el-table v-loading="loading" :data="seqSampleList" highlight-current-row border>
              <el-table-column label="序号" width="55" prop="dataIndex" />
              <el-table-column label="样本编号" prop="number" />
              <el-table-column label="创建时间" prop="createTimeText" />
              <el-table-column label="更新时间" prop="updateTimeText" />
              <el-table-column fixed="right" label="操作" min-width="200" width="200">
                <template #default="scope">
                  <el-button type="success" size="small" link @click="previewReport(scope.row)"><i
                      class="el-icon-view"></i> 预览报告</el-button>
                  <!-- <el-button type="primary" size="small" link @click="rendQrCode(scope.row)"><i
                      class="el-icon-edit-outline"></i> 生成码内容</el-button>
                  <el-button type="warning" size="small" link @click="openQrCodeDialog(scope.row)"
                    :disabled="!scope.row.htmlName"><i class="el-icon-view"></i> 查看二维码</el-button> -->
                </template>
              </el-table-column>
            </el-table>
            <div class="block" style="float: right;">
              <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="queryParams.pageNum" :page-sizes="[10, 20, 50, 100]" :page-size="10"
                layout="total, sizes, prev, pager, next, jumper" :total="total">
              </el-pagination>
            </div>

          </el-tab-pane>

        </el-tabs>
      </div>
    </el-card>

    <el-dialog :visible.sync="qrCodeInfoVisible" title="查看二维码" width="400px" :before-close="closeQrCodeDialog">
      <div>
        <p>供者名称：{{ checkedData.name }}</p>
        <img :src="qrCodeUrl" />
      </div>
    </el-dialog>

    <el-dialog :visible.sync="addCheckUpDialogVisible" title="新增/编辑体检单" width="600px"
      :before-close="closeAddCheckUpDialog">
      <el-form ref="checkupForm" :model="checkupForm" label-width="80px">
        <el-form-item label="Fastq1">
          <el-input v-model="checkupForm.fastq1"></el-input>
        </el-form-item>
        <el-form-item label="Fastq2">
          <el-input v-model="checkupForm.fastq2"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addCheckUp">确 定</el-button>
          <el-button @click="closeAddCheckUpDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :visible.sync="detailCheckUpDialogVisible" title="查看体检单" :before-close="closeDetailCheckUpDialogVisible"
      width="1200px">
      <p style="margin-bottom: 20px; font-size: 14px;">体检编号：{{ checkupForm.number }}</p>
      <el-upload class="upload-demo" drag :action="uploadAction" :headers="headers" multiple>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将体检文件拖到此处，或<em>点击上传体检文件</em></div>
      </el-upload>
      <div v-for="(item, index) in checkupListData" :key="index" style="margin-top: 20px;">
        <div style="display: flex;justify-content: space-between; margin-bottom: 10px; align-items: center;">
          <p>{{ item.itemType }}</p>
          <el-button type="danger" @click="deleteReport(item.id)">删 除</el-button>
        </div>
        <iframe :src="htmlPdUrl[index]" frameborder="0" height="570px" width="100%" class="iframe"></iframe>
      </div>
      <!-- <el-descriptions title="体检样本信息">
                <el-descriptions-item label="Fastq1">{{ checkupForm.fastq1 }}</el-descriptions-item>
                <el-descriptions-item label="Fastq1">{{ checkupForm.fastq1 }}</el-descriptions-item>
            </el-descriptions>
            <el-descriptions title="血常规信息">
                <el-descriptions-item label="xx">xx</el-descriptions-item>
            </el-descriptions> -->
    </el-dialog>

    <el-dialog :visible.sync="showSignInDialog" title="打卡照片查看" width="600px" style="height: 500px;" :close-on-click-modal="false">
      <template v-for="item in showSignInImgUrlList">
        <el-image :key="item.url"
          style="width: 200px; height: 200px"
          :src="item.url" 
          :preview-src-list="item.srcList">
        </el-image>
      </template>
    </el-dialog>

    <el-dialog :visible.sync="previewDialog.visible" :title="previewDialog.title" width="900px"
      :close-on-click-modal="false" :before-close="closePreviewDialog">
      <el-button type="success" size="small" link style="float: right; margin-top: 10px; margin-left: 10px;"
          @click="downlaodPdf()">下载报告</el-button>
      <iframe ref="pdfCotainer" :src="pdfUrl" width="100%" height="620px" style="margin-top: 10px;"></iframe>
    </el-dialog>

  </div>
</template>

<script>
import { formatDate } from '@/utils/formatTime'
import fmtSampleApi from '@/api/fmt/sample'
import fmtDonorApi from '@/api/fmt/donor'
import seqSampleApi from '@/api/sequence/seqSample'
import axios from 'axios'
import checkupReport from '@/views/fmt/donor/detail/checkupReport.vue'

import fmtDonorSignInApi from '@/api/fmt/signIn'

import seqSampleReportApi from '@/api/sequence/seqSampleReport';
export default {
  name: 'fmtUserDetailDesign',
  components: {
    checkupReport
  },
  // props: {
  //     checkedData: {
  //         type: Object,
  //         default: {},
  //     },
  // },
  data() {
    return {
      uploadVisible: false,
      report: "",
      reportFormData: [],
      checkedData: {},
      loading: false,
      activeName: 'first',
      queryParams: {
        pageNum: 0,
        pageSize: 10,
      },
      queryParams2: {
        pageNum: 0,
        pageSize: 10,
      },
      total: 0,
      rules: {},

      seqSampleList: [],

      formData: {},

      qrCodeInfoVisible: false,
      qrCodeUrl: '',

      answerJsonList: [],

      addCheckUpDialogVisible: false,
      detailCheckUpDialogVisible: false,
      checkupForm: {},
      headers: {},
      uploadAction: '',
      checkupListData: [],
      htmlPdUrl: [],
      reportId: "",
      checkup_info: false,
      checkedDataID: "",

      signInList: [],
      showSignInDialog: false,
      showSignInImgUrlList: [],

      previewDialog: {},
      downloadSampleReportId: '',
      pdfUrl: '',
    }
  },
  mounted() {
    this.headers = {
      Authorization: 'Bearer ' + localStorage.getItem('token'),
    };
    fmtDonorApi.get(this.$route.query.id).then((res) => {
      this.checkedData = res.data;
      this.init();
    });
  },
  methods: {
    previewReport (row) {
      this.checkedData = row;
      seqSampleReportApi.newestReport(row.id).then(res => {
        let data = res.data;
        if (data.id) {
          this.$set(this.previewDialog, 'title', '预览样本报告');
          this.$set(this.previewDialog, 'visible', true);
          this.downloadSampleReportId = data.id;
          seqSampleReportApi.downloadReport(data.id).then((res) => {
            const binaryData = [];
            binaryData.push(res);
            let blob = new Blob(binaryData, { type: 'application/pdf' });
            this.pdfUrl = window.URL.createObjectURL(blob) + '#toolbar=0&navpanes=0&scrollbar=0';
          });
        } else {
          this.$message({ message: '当前样本未生成报告，请生成报告之后再查看！', type: 'error' });
        }
      })
    },
    closePreviewDialog () {
      this.$set(this.previewDialog, 'visible', false);
    },
    downlaodPdf () {
      if (this.downloadSampleReportId) {
        seqSampleReportApi.downloadReport(this.downloadSampleReportId).then((res) => {
          const blob = new Blob([res], {
            type: 'application/pdf'
          })
          let link = document.createElement('a')
          let body = document.querySelector('body')
          link.href = window.URL.createObjectURL(blob)
          link.style.display = 'none'
          link.download = this.checkedSample.number + '.pdf'
          body.appendChild(link)
          link.click()
          body.removeChild(link)
          window.URL.revokeObjectURL(link.href)
        });
      } else {
        this.$message({ message: '无可下载报告！', type: 'error' });
      }
      
    },
    openSignInDetail(row, flag) {
      this.showSignInDialog = true;
      let itemTypeMap = row.itemTypeMap;
      let dataList = [];
      this.showSignInImgUrlList = [];
      switch (flag) {
        case 'B':
          dataList = itemTypeMap['BREAKFAST'] ? itemTypeMap['BREAKFAST'] : []
          break;
        case 'L':
          dataList = itemTypeMap['LUNCH'] ? itemTypeMap['LUNCH'] : []
          break;
        case 'D':
          dataList = itemTypeMap['DINNER'] ? itemTypeMap['DINNER'] : []
          break;
        case 'F':
          dataList = itemTypeMap['FECES'] ? itemTypeMap['FECES'] : []
          break;
      }
      for (let i = 0, len = dataList.length; i < len; i++) {
        this.showSignInImgUrlList.push({
          url: dataList[i].imgUrl,
          srcList: [dataList[i].imgUrl]
        });
      }
      console.log(this.showSignInImgUrlList)
    },
    closeDetail() {
      this.checkup_info = false;
    },
    // 体检信息 上传
    uploadReport() {
      this.uploadVisible = true;
    },
    addReportData() {
      this.reportFormData.push({})
    },
    delReportData(index) {
      this.reportFormData.splice(index, 1);
    },
    openDetailCheckUpDialogVisible(id) {
      this.checkedDataID = id;
      this.checkup_info = true;

      // seqSampleApi.get(id).then(res => {
      //     this.detailCheckUpDialogVisible = true;
      //     this.checkupForm = res.data;
      // })
      // this.uploadAction = process.env.VUE_APP_FILE_API_PREV + '/fmt-donor-checkup/upload-item/' + id;

      // this.reportId = id;
      // this.getReportList();
    },
    // 获取体检项列表
    // getReportList() {
    //     seqSampleApi.checkupList(this.reportId).then(res => {
    //         this.checkupListData = res.data;
    //         for (let i = 0; i < this.checkupListData.length; i++) {
    //             axios({
    //                 url: this.checkupListData[i].imgUrl,
    //                 method: 'get',
    //                 responseType: 'blob'
    //             }).then(r => {
    //                 const binaryData = [];
    //                 binaryData.push(r.data);
    //                 let b = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/pdf' })) + '#toolbar=0&navpanes=0&scrollbar=0';
    //                 this.$set(this.htmlPdUrl, i, b);
    //             })
    //         }
    //     })
    // },
    // // 删除体检单
    // deleteReport(id) {
    //     this.$confirm("此操作将删除该体检单，是否继续?", "提示", {
    //         confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
    //     }).then(() => {
    //         seqSampleApi.deleteCheckup(id).then(res => {
    //             if (res.code == 200) {
    //                 if (res.data) {
    //                     this.$message({ message: '操作成功！', type: 'success' });
    //                     this.getReportList();
    //                 }
    //             }
    //         })
    //     }).catch(() => {
    //         // this.$message({ type: 'info', message: '已取消删除' });
    //     });
    // },
    closeDetailCheckUpDialogVisible() {
      this.detailCheckUpDialogVisible = false;
    },
    addCheckUp() {
      this.checkupForm.fmtUserId = this.checkedData.id;
      this.checkupForm.sampleType = 'CHECK_UP';
      if (this.checkupForm.id) {
        seqSampleApi.update(this.checkupForm).then(res => {
          this.$message({ message: '体检信息编辑成功！', type: 'success' });
          this.closeAddCheckUpDialog();
          this.getCheckupSampleList();
        })
      } else {
        seqSampleApi.add(this.checkupForm).then(res => {
          this.$message({ message: '体检信息填写成功！', type: 'success' });
          this.closeAddCheckUpDialog();
          this.getCheckupSampleList();
        })
      }

    },
    openAddCheckUpDialog(id) {
      this.checkupForm = {};
      if (id) {
        seqSampleApi.get(id).then(res => {
          this.addCheckUpDialogVisible = true;
          this.checkupForm = res.data;
        })
      } else {
        this.addCheckUpDialogVisible = true;
      }
    },
    closeAddCheckUpDialog() {
      this.addCheckUpDialogVisible = false;
    },
    rendQrCode(row) {
      fmtSampleApi.renderContent(row.id).then(res => {
        this.$message({ message: '二维码内容生成成功！', type: 'success' });
        this.getSeqSampleList();
      })
    },
    openQrCodeDialog(row) {
      //this.checkedBatch = row;
      fmtSampleApi.qrCode(row.id).then(res => {
        this.qrCodeInfoVisible = true;
        this.qrCodeUrl = window.URL.createObjectURL(res)
      })
    },
    closeQrCodeDialog() {
      this.qrCodeInfoVisible = false;
    },
    init() {
      this.queryParams = {
        pageNum: 0,
        pageSize: 10,
      };
      switch (this.activeName) {
        case 'first':
          let surveyAnswerJson = this.checkedData.surveyAnswerJson;
          if (surveyAnswerJson) {
            let dataJson = JSON.parse(surveyAnswerJson);
            for (let k in dataJson) {
              this.answerJsonList.push({
                key: k,
                val: dataJson[k]
              })
            }
          }
          this.checkup_info = false;
          break;
        case 'second':
          this.getSeqSampleList();
          this.checkup_info = false;
          break;
        case 'third':
          // this.checkup_info = true;
          this.getCheckupSampleList();
          break;
        case 'third2':
          this.checkup_info = false;
          this.getSignInList()
          break;
      }
    },
    getSignInList() {
      this.signInList = [];
      this.loading = true;
      let params = {
        number: this.queryParams.pageNum,
        size: this.queryParams.pageSize,
        fmtUserId: this.checkedData.id
      };
      fmtDonorSignInApi.page(params).then(res => {
        let data = res.data;
        let index = 1
        data.content.forEach((v) => {
          v.dataIndex = index++;
          v.createTimeText = formatDate(new Date(v.createTime), "YYYY-mm-dd")
          v.updateTimeText = formatDate(new Date(v.updateTime), "YYYY-mm-dd HH:MM:SS")
          v.bImgNum = v.itemTypeMap['BREAKFAST'] ? v.itemTypeMap['BREAKFAST'].length : 0
          v.lImgNum = v.itemTypeMap['LUNCH'] ? v.itemTypeMap['LUNCH'].length : 0
          v.dImgNum = v.itemTypeMap['DINNER'] ? v.itemTypeMap['DINNER'].length : 0
          v.fImgNum = v.itemTypeMap['FECES'] ? v.itemTypeMap['FECES'].length : 0
        });
        this.signInList = data.content;

        this.total = data.count;
        this.loading = false;
      })
    },
    getCheckupSampleList() {
      this.seqSampleList = [];
      this.loading = true;
      let searchFormData = [{
        name: 'sampleType',
        searchType: 'EQUAL',
        searchVal: 'CHECK_UP'
      }, {
        name: 'fmtUserId',
        searchType: 'EQUAL',
        searchVal: this.checkedData.id
      }];
      let params = {
        number: this.queryParams.pageNum,
        size: this.queryParams.pageSize,
        criteriaVos: searchFormData,
      };
      seqSampleApi.page(params).then((res) => {
        let data = res.data;
        let index = 1
        data.content.forEach((v) => {
          v.dataIndex = index++;
          v.createTimeText = formatDate(new Date(v.createTime), "YYYY-mm-dd HH:MM:SS")
          v.updateTimeText = formatDate(new Date(v.updateTime), "YYYY-mm-dd HH:MM:SS")
        });
        this.seqSampleList = data.content;

        this.total = data.count;
        this.loading = false;
      }).catch(() => { });
    },
    getSeqSampleList() {
      this.seqSampleList = [];
      this.loading = true;
      let searchFormData = [{
        name: 'sampleType',
        searchType: 'EQUAL',
        searchVal: 'FMT'
      }, {
        name: 'fmtUserId',
        searchType: 'EQUAL',
        searchVal: this.checkedData.id
      }];
      let params = {
        number: this.queryParams.pageNum,
        size: this.queryParams.pageSize,
        criteriaVos: searchFormData,
      };
      seqSampleApi.page(params).then((res) => {
        let data = res.data;
        let index = 1
        data.content.forEach((v) => {
          v.dataIndex = index++;
          v.createTimeText = formatDate(new Date(v.createTime), "YYYY-mm-dd HH:MM:SS")
          v.updateTimeText = formatDate(new Date(v.updateTime), "YYYY-mm-dd HH:MM:SS")
        });
        this.seqSampleList = data.content;

        this.total = data.count;
        this.loading = false;
      }).catch(() => { });
    },
    handleTabsClick(tab, event) {
      this.init()
    },
    // reback() {
    //     // this.$emit("close");
    //     this.$router.push({
    //         path: "/fmt/donor",
    //     })
    // },
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getSeqSampleList();
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getSeqSampleList();
    },
  }
}
</script>